using UnityEngine;
using UnityEngine.UI;
using TMPro;
using System.Collections;

/// <summary>
/// 战斗UI管理器
/// 负责战斗界面的显示和更新
/// </summary>
public class BattleUIManager : MonoBehaviour
{
    [Header("战斗信息UI")]
    [SerializeField] private TextMeshProUGUI battleIdText;
    [SerializeField] private TextMeshProUGUI turnText;
    [SerializeField] private TextMeshProUGUI battleStateText;
    [SerializeField] private GameObject battleStartPanel;
    [SerializeField] private GameObject battleEndPanel;
    [SerializeField] private TextMeshProUGUI battleResultText;
    
    [Header("队伍信息UI")]
    [SerializeField] private Transform team1Panel;
    [SerializeField] private Transform team2Panel;
    [SerializeField] private GameObject characterSlotPrefab;
    
    [Header("行动顺序UI")]
    [SerializeField] private Transform turnOrderPanel;
    [SerializeField] private GameObject turnOrderSlotPrefab;
    
    [Header("动画设置")]
    [SerializeField] private float uiAnimationDuration = 0.5f;
    [SerializeField] private AnimationCurve uiAnimationCurve;
    
    private void Start()
    {
        InitializeUI();
    }
    
    /// <summary>
    /// 初始化UI
    /// </summary>
    private void InitializeUI()
    {
        // 隐藏开始和结束面板
        if (battleStartPanel) battleStartPanel.SetActive(false);
        if (battleEndPanel) battleEndPanel.SetActive(false);
        
        // 清空队伍面板
        if (team1Panel) ClearChildren(team1Panel);
        if (team2Panel) ClearChildren(team2Panel);
        
        // 清空行动顺序面板
        if (turnOrderPanel) ClearChildren(turnOrderPanel);
        
        Debug.Log("战斗UI初始化完成");
    }
    
    /// <summary>
    /// 更新战斗状态
    /// </summary>
    public void UpdateBattleState(BattleStateData battleState)
    {
        if (battleIdText) battleIdText.text = $"战斗ID: {battleState.battleId}";
        if (turnText) turnText.text = $"回合: {battleState.currentTurn}";
        if (battleStateText) battleStateText.text = $"状态: {GetBattleStateDisplayName(battleState.battleState)}";
        
        // 更新队伍信息
        UpdateTeamUI(team1Panel, battleState.teams[0]);
        UpdateTeamUI(team2Panel, battleState.teams[1]);
        
        // 更新行动顺序
        UpdateTurnOrderUI(battleState.turnOrder);
    }
    
    /// <summary>
    /// 显示战斗开始
    /// </summary>
    public void ShowBattleStart(string battleId)
    {
        if (battleStartPanel)
        {
            battleStartPanel.SetActive(true);
            StartCoroutine(ShowBattleStartCoroutine(battleId));
        }
    }
    
    private IEnumerator ShowBattleStartCoroutine(string battleId)
    {
        // 显示战斗开始动画
        yield return new WaitForSeconds(2.0f);
        battleStartPanel.SetActive(false);
    }
    
    /// <summary>
    /// 显示回合开始
    /// </summary>
    public void ShowTurnStart(int turn)
    {
        if (turnText)
        {
            // 播放回合开始动画
            StartCoroutine(PlayTurnStartAnimation(turn));
        }
    }
    
    private IEnumerator PlayTurnStartAnimation(int turn)
    {
        float originalSize = turnText.fontSize;
        turnText.fontSize = (int)(originalSize * 1.5f);
        
        float timer = 0;
        while (timer < uiAnimationDuration)
        {
            timer += Time.deltaTime;
            float progress = timer / uiAnimationDuration;
            turnText.fontSize = Mathf.RoundToInt(Mathf.Lerp(originalSize * 1.5f, originalSize, uiAnimationCurve.Evaluate(progress)));
            yield return null;
        }
        
        turnText.fontSize = originalSize;
    }
    
    /// <summary>
    /// 显示战斗结束
    /// </summary>
    public void ShowBattleEnd(object result)
    {
        if (battleEndPanel)
        {
            battleEndPanel.SetActive(true);
            
            // 解析战斗结果
            if (result is BattleResultData battleResult)
            {
                battleResultText.text = $"队伍 {battleResult.winnerTeamId} 获胜!\n{battleResult.reason}";
            }
            else
            {
                battleResultText.text = "战斗结束!";
            }
        }
    }
    
    /// <summary>
    /// 更新队伍UI
    /// </summary>
    private void UpdateTeamUI(Transform teamPanel, TeamData teamData)
    {
        if (!teamPanel) return;
        
        // 清空现有角色槽位
        ClearChildren(teamPanel);
        
        // 创建角色槽位
        foreach (var character in teamData.characters)
        {
            GameObject slot = Instantiate(characterSlotPrefab, teamPanel);
            CharacterSlotUI slotUI = slot.GetComponent<CharacterSlotUI>();
            
            if (slotUI)
            {
                slotUI.UpdateCharacterData(character);
            }
        }
    }
    
    /// <summary>
    /// 更新行动顺序UI
    /// </summary>
    private void UpdateTurnOrderUI(TurnOrderData[] turnOrder)
    {
        if (!turnOrderPanel) return;
        
        // 清空现有行动顺序
        ClearChildren(turnOrderPanel);
        
        // 创建行动顺序槽位
        foreach (var orderData in turnOrder)
        {
            GameObject slot = Instantiate(turnOrderSlotPrefab, turnOrderPanel);
            TurnOrderSlotUI slotUI = slot.GetComponent<TurnOrderSlotUI>();
            
            if (slotUI)
            {
                slotUI.UpdateTurnOrderData(orderData);
            }
        }
    }
    
    /// <summary>
    /// 获取战斗状态显示名称
    /// </summary>
    private string GetBattleStateDisplayName(string battleState)
    {
        switch (battleState)
        {
            case "waiting": return "等待中";
            case "starting": return "开始中";
            case "in_progress": return "进行中";
            case "ended": return "已结束";
            default: return battleState;
        }
    }
    
    /// <summary>
    /// 清空子对象
    /// </summary>
    private void ClearChildren(Transform parent)
    {
        for (int i = parent.childCount - 1; i >= 0; i--)
        {
            Destroy(parent.GetChild(i).gameObject);
        }
    }
}

/// <summary>
/// 角色槽位UI组件
/// </summary>
public class CharacterSlotUI : MonoBehaviour
{
    [Header("角色信息")]
    [SerializeField] private TextMeshProUGUI characterNameText;
    [SerializeField] private TextMeshProUGUI levelText;
    [SerializeField] private Slider hpSlider;
    [SerializeField] private Slider mpSlider;
    [SerializeField] private TextMeshProUGUI hpText;
    [SerializeField] private TextMeshProUGUI mpText;
    [SerializeField] private GameObject aliveIndicator;
    [SerializeField] private GameObject deadIndicator;
    
    [Header("状态效果")]
    [SerializeField] private Transform statusEffectsPanel;
    [SerializeField] private GameObject statusEffectPrefab;
    
    /// <summary>
    /// 更新角色数据
    /// </summary>
    public void UpdateCharacterData(CharacterData character)
    {
        // 更新基本信息
        if (characterNameText) characterNameText.text = character.name;
        if (levelText) levelText.text = $"Lv.{character.level}";
        
        // 更新HP
        if (hpSlider)
        {
            hpSlider.maxValue = character.maxHp;
            hpSlider.value = character.hp;
        }
        if (hpText) hpText.text = $"{character.hp}/{character.maxHp}";
        
        // 更新MP
        if (mpSlider)
        {
            mpSlider.maxValue = character.maxMp;
            mpSlider.value = character.mp;
        }
        if (mpText) mpText.text = $"{character.mp}/{character.maxMp}";
        
        // 更新生存状态
        if (aliveIndicator) aliveIndicator.SetActive(character.isAlive);
        if (deadIndicator) deadIndicator.SetActive(!character.isAlive);
        
        // 更新状态效果
        UpdateStatusEffects(character.statusEffects);
    }
    
    /// <summary>
    /// 更新状态效果
    /// </summary>
    private void UpdateStatusEffects(StatusEffectData[] statusEffects)
    {
        if (!statusEffectsPanel) return;
        
        // 清空现有状态效果
        for (int i = statusEffectsPanel.childCount - 1; i >= 0; i--)
        {
            Destroy(statusEffectsPanel.GetChild(i).gameObject);
        }
        
        // 添加状态效果
        foreach (var effect in statusEffects)
        {
            GameObject effectObj = Instantiate(statusEffectPrefab, statusEffectsPanel);
            StatusEffectUI effectUI = effectObj.GetComponent<StatusEffectUI>();
            
            if (effectUI)
            {
                effectUI.UpdateStatusEffect(effect);
            }
        }
    }
}

/// <summary>
/// 行动顺序槽位UI组件
/// </summary>
public class TurnOrderSlotUI : MonoBehaviour
{
    [Header("行动顺序信息")]
    [SerializeField] private TextMeshProUGUI characterNameText;
    [SerializeField] private TextMeshProUGUI speedText;
    [SerializeField] private Image backgroundImage;
    [SerializeField] private Color currentTurnColor = Color.yellow;
    [SerializeField] private Color normalTurnColor = Color.white;
    
    /// <summary>
    /// 更新行动顺序数据
    /// </summary>
    public void UpdateTurnOrderData(TurnOrderData orderData)
    {
        if (characterNameText) characterNameText.text = orderData.characterName;
        if (speedText) speedText.text = $"速度: {orderData.speed}";
        
        // 这里可以根据当前行动角色来高亮显示
        // 暂时使用默认颜色
        if (backgroundImage) backgroundImage.color = normalTurnColor;
    }
    
    /// <summary>
    /// 设置为当前行动角色
    /// </summary>
    public void SetCurrentTurn(bool isCurrent)
    {
        if (backgroundImage) backgroundImage.color = isCurrent ? currentTurnColor : normalTurnColor;
    }
}

/// <summary>
/// 状态效果UI组件
/// </summary>
public class StatusEffectUI : MonoBehaviour
{
    [Header("状态效果信息")]
    [SerializeField] private Image iconImage;
    [SerializeField] private TextMeshProUGUI durationText;
    [SerializeField] private TextMeshProUGUI stacksText;
    
    /// <summary>
    /// 更新状态效果
    /// </summary>
    public void UpdateStatusEffect(StatusEffectData effect)
    {
        // 根据状态效果名称设置图标
        if (iconImage) iconImage.sprite = GetStatusEffectIcon(effect.name);
        
        // 显示持续时间
        if (durationText) durationText.text = effect.duration > 0 ? effect.duration.ToString() : "";
        
        // 显示堆叠层数
        if (stacksText) stacksText.text = effect.stacks > 1 ? effect.stacks.ToString() : "";
    }
    
    /// <summary>
    /// 获取状态效果图标
    /// </summary>
    private Sprite GetStatusEffectIcon(string effectName)
    {
        // 这里应该根据状态效果名称返回对应的图标
        // 暂时返回null，使用默认图标
        return null;
    }
}